//
//  DownLoadManager.m
//  CapriceMusic
//
//  Created by dllo on 16/1/19.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "DownLoadManager.h"

@implementation DownLoadManager


static DownLoadManager *downLoad = nil;

+ (instancetype)shareDownLoadManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downLoad = [[DownLoadManager alloc] init];
    });
    return downLoad;
}

/**
 *  下载完毕后调用
 *
 *
 *  @param location     文件临时地址
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    NSLog(@"%@",file);
    
    
    self.isdownloading = NO;
    self.dataBaseHandle = [DataBaseHandle shareDataBase];
    [self.dataBaseHandle openDataBase];
    [self.dataBaseHandle createDownloadAlreadyTable];
    [self.dataBaseHandle selectdownloading];
    [self.dataBaseHandle insertDownloadAlreadyDatabase:self.dataBaseHandle.downloadingTitle.lastObject withPicture:self.dataBaseHandle.downloadingPicture.lastObject withAddress:file];
    [self.dataBaseHandle deleteDownloading:self.dataBaseHandle.downloadingTitle.lastObject];
    [self.dataBaseHandle selectdownloading];
    [self.dataBaseHandle closedDataBase];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"end" object:nil];
}

/**
 *  每次写入沙盒完毕调用
 *  在这里面监听下载进度，totalBytesWritten/totalBytesExpectedToWrite
 *  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入沙盒的大小
 *  @param totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
        NSLog(@"%f",(float)totalBytesWritten/totalBytesExpectedToWrite * 100);
//    downLoadManager.num = (float)totalBytesWritten/totalBytesExpectedToWrite;
//    NSLog(@"%f",downLoadManager.num);
    self.num = (float)totalBytesWritten/totalBytesExpectedToWrite;
    NSString *str = [NSString stringWithFormat:@"%f",(float)totalBytesWritten/totalBytesExpectedToWrite];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"progress" object:str];
    
}

- (void)downLoad:(NSString *)url {
    NSURL *downloadurl = [NSURL URLWithString:url];
    NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.downloadTask = [self.session downloadTaskWithURL:downloadurl];
    [_downloadTask resume];
    self.isdownloading = YES;
}


@end



